import { defineStore } from 'pinia'
import type { AdminStats } from '../types/admin'
import type { User } from '../types/user'
import type { Post } from '../types/forum'
import type { Question } from '../types/question'
import type { StudyGroup as LearningGroup } from '../types/group'
import type { LearningResource } from '../types/resource'
import { getAdminStats } from '../api/admin'
import { getUserList, updateUserStatus } from '../api/user'
import { getPosts, deletePost as adminDeletePost } from '../api/forum'
import { searchQuestions, deleteQuestion } from '../api/question'
import { getAllGroups as getGroups, deleteGroup } from '../api/group'
import { getHotResources, deleteResource } from '../api/resource'

interface AdminState {
  stats: AdminStats | null
  users: User[]
  posts: Post[]
  questions: Question[]
  groups: LearningGroup[]
  resources: LearningResource[]
  userPagination: { currentPage: number; total: number; pageSize: number }
  postPagination: { currentPage: number; total: number; pageSize: number }
  questionPagination: { currentPage: number; total: number; pageSize: number }
  groupPagination: { currentPage: number; total: number; pageSize: number }
  resourcePagination: { currentPage: number; total: number; pageSize: number }
  isLoading: boolean
  error: string | null
}

export const useAdminStore = defineStore('admin', {
  state: (): AdminState => ({
    stats: null,
    users: [],
    posts: [],
    questions: [],
    groups: [],
    resources: [],
    userPagination: { currentPage: 1, total: 0, pageSize: 20 },
    postPagination: { currentPage: 1, total: 0, pageSize: 20 },
    questionPagination: { currentPage: 1, total: 0, pageSize: 20 },
    groupPagination: { currentPage: 1, total: 0, pageSize: 20 },
    resourcePagination: { currentPage: 1, total: 0, pageSize: 20 },
    isLoading: false,
    error: null
  }),
  
  getters: {
    // 获取统计数据概览
    statsOverview: (state): any => {
      return state.stats ? {
        totalUsers: state.stats.totalUsers,
        activeUsers: state.stats.activeUsers,
        totalPosts: state.stats.totalPosts,
        totalQuestions: state.stats.totalQuestions,
        totalGroups: state.stats.totalGroups,
        totalResources: state.stats.totalResources,
        newUsersToday: state.stats.newUsersToday,
        newPostsToday: state.stats.newPostsToday
      } : null
    },
    
    // 获取禁用用户列表
    bannedUsers: (state): User[] => {
      return state.users.filter(user => user.status !== 'ACTIVE')
    },
    
    // 获取未审核的帖子列表
    pendingPosts: (state): Post[] => {
      return state.posts.filter(post => post.status === 'PENDING')
    }
  },
  
  actions: {
    // 获取后台统计数据
    async fetchAdminStats() {
      try {
        this.isLoading = true
        this.error = null
        const stats = await getAdminStats()
        this.stats = stats
        return stats
      } catch (error: any) {
        this.error = error.message || '获取统计数据失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取所有用户列表
    async fetchAllUsers(params?: {
      keyword?: string
      enabled?: boolean
      isAdmin?: boolean
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        const result = await getUserList(params || {})
        this.users = result.list
        this.userPagination = {
          currentPage: params?.page || 1,
          total: result.total,
          pageSize: params?.pageSize || 10
        }
        return {
          items: result.list,
          currentPage: params?.page || 1,
          total: result.total,
          pageSize: params?.pageSize || 10
        }
      } catch (error: any) {
        this.error = error.message || '获取用户列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 更新用户状态（启用/禁用）
    async toggleUserStatus(userId: number) {
      try {
        this.isLoading = true
        const user = this.users.find(u => u.id === userId)
        if (user) {
          const newStatus = user.status === 'ACTIVE' ? 'BANNED' : 'ACTIVE'
          await updateUserStatus(userId, newStatus)
          user.status = newStatus
        }
        return { success: true }
      } catch (error: any) {
        this.error = error.message || '更新用户状态失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    
    // 获取所有帖子列表
    async fetchAllPosts(params?: {
      keyword?: string
      status?: 'APPROVED' | 'PENDING' | 'REJECTED'
      userId?: number
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        const result = await getPosts(params || {})
        this.posts = result.items
        this.postPagination = {
          currentPage: result.currentPage,
          total: result.total,
          pageSize: result.pageSize
        }
        return result
      } catch (error: any) {
        this.error = error.message || '获取帖子列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除帖子（管理员操作）
    async deleteAdminPost(postId: number) {
      try {
        this.isLoading = true
        const response = await adminDeletePost(postId)
        // 从列表中移除帖子
        this.posts = this.posts.filter(post => post.id !== postId)
        // 更新分页信息
        this.postPagination.total -= 1
        return response
      } catch (error: any) {
        this.error = error.message || '删除帖子失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取所有题目列表
    async fetchAllQuestions(params?: {
      keyword?: string
      categoryId?: number
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        const result = await searchQuestions(params as any)
        this.questions = Array.isArray(result) ? result : []
        this.questionPagination = {
          currentPage: 1,
          total: Array.isArray(result) ? result.length : 0,
          pageSize: 20
        }
        return result
      } catch (error: any) {
        this.error = error.message || '获取题目列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除题目
    async deleteAdminQuestion(questionId: number) {
      try {
        this.isLoading = true
        const response = await deleteQuestion(questionId)
        // 从列表中移除题目
        this.questions = this.questions.filter(question => question.id !== questionId)
        // 更新分页信息
        this.questionPagination.total -= 1
        return response
      } catch (error: any) {
        this.error = error.message || '删除题目失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取所有学习小组列表
    async fetchAllGroups(params?: {
      keyword?: string
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        const result = await getGroups(params || {})
        this.groups = result.content || []
        this.groupPagination = {
          currentPage: 1,
          total: result.totalElements || 0,
          pageSize: 10
        }
        return result
      } catch (error: any) {
        this.error = error.message || '获取学习小组列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除学习小组
    async deleteAdminGroup(groupId: number) {
      try {
        this.isLoading = true
        const response = await deleteGroup(groupId)
        // 从列表中移除小组
        this.groups = this.groups.filter((group: LearningGroup) => group.id !== groupId)
        // 更新分页信息
        this.groupPagination.total -= 1
        return response
      } catch (error: any) {
        this.error = error.message || '删除小组失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取热门学习资源列表
    async fetchAllResources(params?: {
      keyword?: string
      categoryId?: number
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        // 使用热门资源API作为替代
        const result = await getHotResources(params?.pageSize || 10)
        this.resources = result
        this.resourcePagination = {
          currentPage: 1,
          total: result.length,
          pageSize: result.length
        }
        return { items: result, currentPage: 1, total: result.length, pageSize: result.length }
      } catch (error: any) {
        this.error = error.message || '获取学习资源列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除学习资源
    async deleteAdminResource(resourceId: number) {
      try {
        this.isLoading = true
        const response = await deleteResource(resourceId)
        // 从列表中移除资源
        this.resources = this.resources.filter((resource: LearningResource) => resource.id !== resourceId)
        // 更新分页信息
        this.resourcePagination.total -= 1
        return response
      } catch (error: any) {
        this.error = error.message || '删除资源失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 清除错误
    clearError() {
      this.error = null
    },
    
    // 刷新所有数据（用于后台概览页面）
    async refreshAllData() {
      try {
        this.isLoading = true
        // 并行获取所有数据
        await Promise.all([
          this.fetchAdminStats(),
          this.fetchAllUsers({ page: 1, pageSize: 10 }),
          this.fetchAllPosts({ page: 1, pageSize: 10 }),
          this.fetchAllQuestions({ page: 1, pageSize: 10 }),
          this.fetchAllGroups({ page: 1, pageSize: 10 }),
          this.fetchAllResources({ page: 1, pageSize: 10 })
        ])
      } catch (error: any) {
        this.error = error.message || '刷新数据失败'
        throw error
      } finally {
        this.isLoading = false
      }
    }
  }
})